package com.TeacherInfoServer.listener;

import com.TeacherInfoServer.exception.JobNumberRepeatedDetailException;
import com.TeacherInfoServer.exception.RecordExistDetailException;
import com.TeacherInfoServer.exception.TeacherNameNotExistException;
import com.TeacherInfoServer.exception.TypeInfoNotExistException;
import com.TeacherInfoServer.pojo.entity.Department;
import com.TeacherInfoServer.pojo.entity.PositionHistory;
import com.TeacherInfoServer.pojo.entity.Teacher;
import com.TeacherInfoServer.pojo.excelImport.PositionHistoryExcel;
import com.TeacherInfoServer.common.service.DepartmentService;
import com.TeacherInfoServer.common.service.PositionHistoryService;
import com.TeacherInfoServer.common.service.TeacherService;
import com.TeacherInfoServer.common.service.TypeInfoService;
import com.TeacherInfoServer.utils.ExcelFormatDateUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Data
@Slf4j
@Component
public class PositionHistoryListener implements ReadListener<PositionHistoryExcel> {
    @Autowired
    private PositionHistoryService positionHistoryService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    public TypeInfoService typeInfoService;
    @Autowired
    private Validator validator;
    private final List<PositionHistory> positionHistoryList = new ArrayList<>();
    private final List<PositionHistory> updateList = new ArrayList<>();
    private final List<PositionHistory> addList = new ArrayList<>();
    private final Set<PositionHistoryExcel> positionHistorySet = new HashSet<>();
    private Integer record;

    @Override
    public void invoke(PositionHistoryExcel positionHistoryExcel, AnalysisContext analysisContext) {
        Set<ConstraintViolation<PositionHistoryExcel>> violations = validator.validate((positionHistoryExcel));
        if (violations.isEmpty()){
            if(departmentService.findDepartmentByName(positionHistoryExcel.getDepartmentName())!=null){
                if(teacherService.findTeacherByName(positionHistoryExcel.getTeacherName())!=null){
                    if(!positionHistorySet.contains(positionHistoryExcel)){
                        // 格式化 GraduationDate
                        String formattedStartDate = ExcelFormatDateUtil.formatDate(positionHistoryExcel.getStartDate());
                        if (formattedStartDate == null) {
                            throw new IllegalArgumentException("日期格式无效: " + positionHistoryExcel.getStartDate());
                        }
                        String formattedEndDate = ExcelFormatDateUtil.formatDate(positionHistoryExcel.getEndDate());
                        if (formattedEndDate == null) {
                            throw new IllegalArgumentException("日期格式无效: " + positionHistoryExcel.getEndDate());
                        }
                        if(getTypeInfoService().getOneId("任职类型",positionHistoryExcel.getPositionType())!=null){
                            throw new TypeInfoNotExistException("任职类型："+positionHistoryExcel.getPositionType()+"不存在");
                        }
                        Department department=departmentService.findDepartmentByName(positionHistoryExcel.getDepartmentName());
                        Teacher teacher =teacherService.findTeacherByName(positionHistoryExcel.getTeacherName());
                        PositionHistory positionHistory =new PositionHistory(null,
                                department.getId(),
                                formattedStartDate,
                                formattedEndDate,
                                teacher.getTeacherId(),
                                typeInfoService.getOneId("任职类型",positionHistoryExcel.getPositionType()));
                        positionHistoryList.add(positionHistory);
                        positionHistorySet.add(positionHistoryExcel);
                    }else {
                        throw new RecordExistDetailException("表中存在完全相同记录");
                    }
                }else {
                    throw new TeacherNameNotExistException("文件中有教师"+positionHistoryExcel.getTeacherName()+"存在");
                }
            }else {
                throw new JobNumberRepeatedDetailException("表中教研室："+positionHistoryExcel.getDepartmentName()+"不存在");
            }

        }else {
            String errorMessage = violations.iterator().next().getMessage();
            throw new ConstraintViolationException(errorMessage, violations);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        List<PositionHistory> positionHistories = positionHistoryService.list();
        positionHistoryList.forEach(positionHistory -> {
            Optional<PositionHistory> positionHistoryOptional = positionHistories.stream()
                    .peek(dbPositionHistory -> dbPositionHistory.setId(null))
                    .filter(positionHistory::equals)
                    .findFirst();
            positionHistoryOptional.ifPresent(dbPositionHistory -> log.info("记录已存在数据库:{}",dbPositionHistory));
            if(positionHistoryOptional.isEmpty()){
                addList.add(positionHistory);

            }

        });
        List<PositionHistory> mergedList = Stream.concat(updateList.stream(),addList.stream()).collect(Collectors.toList());
        positionHistoryService.saveOrUpdateBatch(mergedList);
        setRecord(mergedList.size());
        initList();
    }
    public void initList(){
        positionHistoryList.clear();
        updateList.clear();
        addList.clear();
        positionHistorySet.clear();
    }
}
